package com.alennus.blog.service;

import com.alennus.blog.domain.Account;
import com.alennus.blog.domain.Record;
import com.alennus.blog.dto.MediaDto;
import com.alennus.blog.repository.RecordRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageImpl;
import org.springframework.data.domain.Pageable;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;
import org.thymeleaf.util.StringUtils;

import java.util.List;

/**
 * Created by pactera on 2018/7/19.
 */
@Service
public class RecordService {


    @Autowired
    private RecordRepository recordRepository;

    @Autowired
    private AccountService accountService;

    @Autowired
    private MongoTemplate template;

    @Value("${media.server.url}")
    private String mediaServerUrl;

    public Record save(Record record){
        return recordRepository.save(record);
    }

    public Page<Record> findRecord(Record record, Pageable pageable){
        Criteria criteria = new Criteria();
//        if(!StringUtils.isEmpty(menu.getParentId())){
//            criteria.and("parentId").is(menu.getParentId());
//        }
        Query query = new Query(criteria);
        //查询
        List<Record> list = template.find(query.with(pageable), Record.class);
        for(Record selectRecord : list){
            String icon = selectRecord.getIcon();
            if(StringUtils.isEmpty(icon)){
                icon = "default.jpg";
            }
            MediaDto mediaDto = new MediaDto();
            mediaDto.setUrl(new StringBuffer(mediaServerUrl).append("/").append(icon).toString());
            selectRecord.setMediaDto(mediaDto);
            //查询修改人与添加人
            String createUserId = selectRecord.getCreateUserId();
            if(!StringUtils.isEmptyOrWhitespace(createUserId)){
                Account createAccount = accountService.findByID(createUserId);
                selectRecord.setCreateAccount(createAccount);
            }
            String updateUserId = selectRecord.getUpdateUserId();
            if(!StringUtils.isEmptyOrWhitespace(updateUserId)){
                Account updateAccount = accountService.findByID(updateUserId);
                selectRecord.setUpdateAccount(updateAccount);
            }
        }

        Long count =  template.count(query, Record.class);
        //将集合与分页结果封装
        return new PageImpl<Record>(list, pageable, count);
    }

    public void delete(List<Record> records){
        recordRepository.deleteAll(records);
    }


}
